import { ref } from "vue";
import { defineQueryOptions, defineQuery, useQuery } from "@pinia/colada";

import { findCourses, findCourse } from "@/apis/course";
import { type PaginationParams } from "@/apis";

// 使用 COURSE_QUERY_KEY 来定义查询键, 集中管理 keys
export const COURSE_QUERY_KEY = {
  root: ["course"] as const,
  list: (params: PaginationParams) =>
    [...COURSE_QUERY_KEY.root, "list", { ...params }] as const,
  item: (id: number) => [...COURSE_QUERY_KEY.root, id] as const,
};

export const findCoursesOptions = defineQueryOptions(
  (params: PaginationParams) => ({
    key: COURSE_QUERY_KEY.list(params),
    query: () => findCourses(params),
    placeholderData: (keepPreviousData: any) => keepPreviousData,
  })
);

// 全局的科目查询
export const useFindCourses = defineQuery(() => {
  const pageParams = ref<PaginationParams>({
    page: 1,
    pageSize: 4,
  });
  const query = useQuery(findCoursesOptions, () => ({
    ...pageParams.value,
  }));
  return {
    ...query,
    pageParams,
  };
});

// 使用在 Course 详情页
export const findCourseOptions = defineQueryOptions((id: number) => ({
  key: COURSE_QUERY_KEY.item(id),
  query: () => findCourse(id),
}));
export const useFindCourse = defineQuery(() => {
  const courseId = ref<number>(0);
  const query = useQuery(findCourseOptions, () => courseId.value);
  return {
    ...query,
    courseId,
  };
});
